package parser

import (
	"GraduationProject/public/models"
	"GraduationProject/worker/fengchedm/fengchedm_conf"
	"encoding/json"
	"regexp"
	"strconv"
)

var (
	animeRegex         = regexp.MustCompile(`<li><a[^<]*<img[^>]*></a>[^<]*<p>[^<]*<a href="([^"]*)" title="([^"]*)">[^<]*</a></p>[^<]*<p>([^<]*)</p>`)
	animeNextPageRegex = regexp.MustCompile(`<a style='color:red'[^>]*><em>[^>]*></a><a href="([^"]*)">\[([^]])]</a>`)
)

func Anime(seed models.Record, content []byte) (seeds []models.Record, results []models.Record) {
	animes := animeRegex.FindAllStringSubmatch(string(content), -1)
	next := animeNextPageRegex.FindAllStringSubmatch(string(content), 1)

	//fmt.Println(animes)
	//fmt.Println(next)

	rst, err := json.Marshal(animes)
	if err != nil {
		seed.Error = err.Error()
	} else {
		seed.Result = string(rst)
	}

	results = []models.Record{
		seed,
	}

	seeds = make([]models.Record, 0, len(animes)+1)

	if len(next) == 1 {
		seeds = append(seeds, models.Record{
			NotElastic:   true,
			SeedID:       seed.ID,
			Url:          fengchedm_conf.Prefix + next[0][1],
			FunctionName: fengchedm_conf.FengchedmAnime,
			UniqueKey:    strconv.Itoa(int(seed.ID)) + "-" + fengchedm_conf.Prefix + next[0][1],
		})
	}

	for _, v := range animes {
		seeds = append(seeds, models.Record{
			NotElastic:   true,
			SeedID:       seed.ID,
			Url:          fengchedm_conf.Prefix + v[1],
			FunctionName: fengchedm_conf.FengchedmDetail,
			Remarks:      v[2],
		})
	}

	return seeds, results
}
